package com.hyc.fengqiao.controller;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.hyc.fengqiao.enums.ServiceCodeeEnum;
import com.hyc.fengqiao.util.MessageDigestUtil;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
public class OrderController {
    private final static String fengQiaoUrl = "https://sfapi-sbox.sf-express.com/std/service";
    private final static String partnerID = "HYCl";
    private final static String checkCode = "7ZefN9MavSXtpg3Z1yQIm0aDz0zyDOyu";
    private final static String monthCardNo = "7551234567";
    private final static String orderId = "hyctest000000005";

    @GetMapping(value = "createOrder")
    public String createOrder() throws IOException {
        JSONObject jso = new JSONObject();

        jso.put("language", "zh_CN");
        jso.put("orderId", orderId);

        JSONArray cargoArr = new JSONArray();
        JSONObject cargoFirst = new JSONObject();
        cargoFirst.put("count", 2);
        cargoFirst.put("unit", "台");
        cargoFirst.put("weight", 8.5);
        cargoFirst.put("amount", 10000);
        cargoFirst.put("currency", "CNY");
        cargoFirst.put("name","电脑");
        cargoFirst.put("sourceArea","CHN");
        cargoArr.add(cargoFirst);

        jso.put("cargoDetails", cargoArr);

        JSONArray conArr = new JSONArray();
        JSONObject to = new JSONObject();
        to.put("address", "江苏省南京市雨花台区花神大道66号");
        to.put("contact", "老李");
        to.put("contactType", 1);
        to.put("country", "CN");
        to.put("mobile", "13260881270");

        JSONObject from = new JSONObject();
        from.put("address", "江苏省常州市天宁区雨花三村");
        from.put("company", "苏苏有限公司");
        from.put("contact", "小王");
        from.put("contactType", 2);
        from.put("country", "CN");
        from.put("mobile", "13770811890");

        conArr.add(to);
        conArr.add(from);

        jso.put("contactInfoList", conArr);

        String msgData = jso.toString();
        System.out.println(msgData);
        long timestamp = System.currentTimeMillis();
        String msgDigest = MessageDigestUtil.getDigest(msgData, checkCode, String.valueOf(timestamp));

        String serviceCode = ServiceCodeeEnum.CREATE_ORDER.getCode();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("partnerID", partnerID);
        paramMap.put("requestID", orderId);
        paramMap.put("serviceCode", serviceCode);
        paramMap.put("timestamp", timestamp);
        paramMap.put("msgDigest", msgDigest);
        paramMap.put("msgData", msgData);
        paramMap.put("monthlyCard", monthCardNo);

        //String res = HttpRequest.post(fengQiaoUrl).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8").form(paramMap).execute().body();
        String res = postData(fengQiaoUrl,paramMap);
        JSONObject resObj = JSONObject.fromObject(res);
        if (resObj != null && "A1000".equals(resObj.getString("apiResultCode"))) {
            String respStr = resObj.getString("apiResultData");
            JSONObject resp = JSONObject.fromObject(respStr);
            if (resp != null && resp.getBoolean("success") && resp.getJSONObject("msgData") != null && resp.getJSONObject("msgData").getJSONArray("waybillNoInfoList") != null) {// 成功
                JSONArray waybillNoArr = resp.getJSONObject("msgData").getJSONArray("waybillNoInfoList");
                for (int i = 0; i < waybillNoArr.size(); i++) {
                    Object waybill = waybillNoArr.get(i);
                    JSONObject wayBillObj = JSONObject.fromObject(waybill);
                    Integer billType = wayBillObj.getInt("waybillType");
                    if (1 == billType) {
                        String billNo = wayBillObj.getString("waybillNo");
                        System.out.println(billNo);
                    }
                }
            }
        }

        return res;
    }

    @GetMapping(value = "confrimOrder")
    public String confrimOrder(String waybillNo) throws IOException {
        JSONObject jso = new JSONObject();
        jso.put("orderId", orderId);
        jso.put("dealType", 1);

        JSONArray waybillArr = new JSONArray();
        JSONObject waybill = new JSONObject();
        waybill.put("waybillNo", waybillNo);
        waybill.put("waybillType", 1);
        waybillArr.add(waybill);
        jso.put("waybillNoInfoList", waybillArr);

        String msgData = jso.toString();
        System.out.println(msgData);
        long timestamp = System.currentTimeMillis();
        String msgDigest = MessageDigestUtil.getDigest(msgData, checkCode, String.valueOf(timestamp));

        String serviceCode = ServiceCodeeEnum.UPDATE_ORDER.getCode();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("partnerID", partnerID);
        paramMap.put("requestID", orderId);
        paramMap.put("serviceCode", serviceCode);
        paramMap.put("timestamp", timestamp);
        paramMap.put("msgDigest", msgDigest);
        paramMap.put("msgData", msgData);
        paramMap.put("monthlyCard", monthCardNo);

        //String res = HttpRequest.post(fengQiaoUrl).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8").form(paramMap).execute().body();
        String res = postData(fengQiaoUrl,paramMap);
        return res;
    }

    @GetMapping(value = "cancelOrder")
    public String cancelOrder() throws IOException {
        JSONObject jso = new JSONObject();
        jso.put("orderId", orderId);
        jso.put("dealType", 2);

        String msgData = jso.toString();
        System.out.println(msgData);
        long timestamp = System.currentTimeMillis();
        String msgDigest = MessageDigestUtil.getDigest(msgData, checkCode, String.valueOf(timestamp));

        String serviceCode = ServiceCodeeEnum.UPDATE_ORDER.getCode();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("partnerID", partnerID);
        paramMap.put("requestID", orderId);
        paramMap.put("serviceCode", serviceCode);
        paramMap.put("timestamp", timestamp);
        paramMap.put("msgDigest", msgDigest);
        paramMap.put("msgData", msgData);
        paramMap.put("monthlyCard", monthCardNo);

        //String res = HttpRequest.post(fengQiaoUrl).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8").form(paramMap).execute().body();
        String res = postData(fengQiaoUrl,paramMap);
        return res;
    }


    /**
     * 发送EBS接口
     *
     * @param svcUrlStr
     * @return
     * @throws IOException
     */
    public static String postData(String svcUrlStr, Map<String, Object> params) throws IOException {
        // post参数
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String,Object> param : params.entrySet()) {
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")).append("&");
        }
        if (!postData.toString().equals("")) {
            postData.deleteCharAt(postData.length() - 1);
        }
        byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
        URL url = new URL(svcUrlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        conn.setRequestProperty("Accept", "application/json");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
        wr.write((new String(postDataBytes, StandardCharsets.UTF_8)).toCharArray());
        wr.flush();
        wr.close();
        conn.connect();
        String back = readHttpResponse(conn);
        conn.disconnect();
        return back;
    }

    /**
     *  解析返回值
     * @param conn
     * @return
     */
    public static String readHttpResponse(HttpURLConnection conn) {
        InputStream is = null;
        BufferedReader rd = null;
        StringBuffer response = new StringBuffer();
        try {
            if (conn.getResponseCode() >= 400) {
                is = conn.getErrorStream();
            } else {
                is = conn.getInputStream();
            }
            rd = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = rd.readLine()) != null) {
                line = new String(line.getBytes(), "UTF-8");
                response.append(line);
                response.append('\n');
            }
        } catch (IOException ioe) {
            response.append(ioe.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
            if (rd != null) {
                try {
                    rd.close();
                } catch (Exception e) {
                }
            }
        }
        return (response.toString());
    }


    public static void main(String[] args) {
        String jsonStr = "{\"success\":true,\"errorCode\":\"S0000\",\"errorMsg\":null,\"msgData\":{\"orderId\":\"hyctest000000003\",\"originCode\":\"025\",\"destCode\":\"519\",\"filterResult\":2,\"remark\":\"\",\"url\":null,\"paymentLink\":null,\"isUpstairs\":null,\"isSpecialWarehouseService\":null,\"mappingMark\":null,\"agentMailno\":null,\"returnExtraInfoList\":null,\"waybillNoInfoList\":[{\"waybillType\":1,\"waybillNo\":\"SF7444408955983\"}],\"routeLabelInfo\":[{\"code\":\"1000\",\"routeLabelData\":{\"waybillNo\":\"SF7444408955983\",\"sourceTransferCode\":\"\",\"sourceCityCode\":\"025\",\"sourceDeptCode\":\"025\",\"sourceTeamCode\":\"\",\"destCityCode\":\"519\",\"destDeptCode\":\"519\",\"destDeptCodeMapping\":\"\",\"destTeamCode\":\"\",\"destTeamCodeMapping\":\"\",\"destTransferCode\":\"519\",\"destRouteLabel\":\"519\",\"proName\":\"顺丰标快\",\"cargoTypeCode\":\"C201\",\"limitTypeCode\":\"T4\",\"expressTypeCode\":\"B1\",\"codingMapping\":\"\",\"codingMappingOut\":\"B07\",\"xbFlag\":\"0\",\"printFlag\":\"000000000\",\"twoDimensionCode\":\"MMM={'k1':'519','k2':'519','k3':'','k4':'T4','k5':'SF7444408955983','k6':'A','k7':'f87195c4'}\",\"proCode\":\"T4\",\"printIcon\":\"00000000\",\"abFlag\":\"A\",\"destPortCode\":\"\",\"destCountry\":\"\",\"destPostCode\":\"\",\"goodsValueTotal\":\"\",\"currencySymbol\":\"\",\"cusBatch\":\"\",\"goodsNumber\":\"\",\"errMsg\":\"\",\"checkCode\":\"f87195c4\",\"proIcon\":\"\",\"fileIcon\":\"\",\"fbaIcon\":\"\",\"icsmIcon\":\"\",\"destGisDeptCode\":\"519\",\"newIcon\":null},\"message\":\"SF7444408955983:\"}],\"contactInfoList\":null}}";
        JSONObject resp = JSONObject.fromObject(jsonStr);
        System.out.println(resp.getString("errorMsg"));
    }
}

